<template>
	<view class="chat">
		<!-- 顶部标题 -->
		<view style="width: 100%;height: 10rpx;line-height: 10rpx;	display: flex;justify-content: space-between;">
			<u-popup :show="historyVisible" mode="left" @close="closeHistory" closeable>
				<view style="display: flex; width:300px;">
					<view style="font-size: 14px; line-height: 40px; flex:1; text-align: center;padding-right:5px">历史会话
					</view>
				</view>
				<view class="history-wraper">
					<view style="padding: 0px 20px; overflow-y: auto;">
						<view style="margin-bottom: 20px;">
							<view class="history_section">今天</view>
							<view style="background-color: #FFF; border-radius: 5px;  padding: 2px 5px;">
								<view style="margin-bottom: 10px;" v-for="(item,index) in history.today" :key="index"
									@click="handleViewHistory(item)">
									<view style="color: #8c8c8c; line-height:15px;">{{item.content}}</view>
								</view>
							</view>
						</view>
						<view>
							<view class="history_section">昨天</view>
							<view style="background-color: #FFF; border-radius: 5px;  padding: 2px 5px;">
								<view style="margin-bottom: 10px;" v-for="(item,index) in history.yesterday"
									:key="index" @click="handleViewHistory(item)">
									<view style="color: #8c8c8c;">{{item.content}}</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</u-popup>
		</view>

		<!--聊天消息滚动区域-->
		<scroll-view scroll-with-animation :style="{height: `${windowHeight-inputHeight-160}rpx`}" id="scrollview"
			scroll-y="true" :scroll-top="scrollTop" class="scroll-view">
			<!-- 聊天主体 -->
			<view id="msglistview">
				<!--顶部logo-->
				<view class="container" style="text-align: center;">
					<image class="logo" src="/static/logo.png"></image>
					<view class="logo-title">耒耜AI大模型</view>
					<text style="text-align: center;"></text>
				</view>

				<view class="news-wraper"
					style="background-color: #f4f4f4; margin: 15px 20px; padding: 20px; border-radius: 10px;">
					<view class="news-header" style="display: flex; font-size: 13px; font-style: italic;">
						<view style="flex: 1;">今日精选</view>
						<view>{{date}} {{weekday}}</view>
					</view>
					<view class="news-content" style="margin-top: 20px;">
						<view class="news-item" v-for="(item,index) in articles" :key="index">
							<router-link>{{index+1}}. {{item.title}}</router-link>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>


		<!-- 底部消息发送栏 -->
		<!-- 用来占位，防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
			<view class="send-msg" :style="{bottom:`${keyboardHeight}rpx`}">
				<view class="uni-textarea"
					:style="isRecording? (isCancel ? 'background-color:#ff0000;color:#FFFFFF;':'background-color:#0ac6ff;color:#FFFFFF;'):'background-color:#f0f0f0;color:#333'">
					<view style="display:flex; width: 100%; position: absolute; bottom:110rpx;padding: 4px 6px;">
						<view
							style="padding: 4px 6px; height: 20px; line-height: 20rpx; font-size: 10px; color: #333; background-color: #e6e6e6; border-radius: 5px;"
							@click="openHistory">
							历史会话
						</view>

						<view
							style="padding: 4px 6px; margin-left:5px; height: 20px; line-height: 20rpx; font-size: 10px; color: #333; background-color: #e6e6e6; border-radius: 5px;"
							@click="createChat">
							新建会话
						</view>
					</view>


					<!--语音聊天-->
					<view v-if="inputType=='voice'" style="display: flex;">
						<view style="padding: 5px 10px;" v-if="!isRecording" @click="handleSwitchInputType">
							<u-icon name="mic" size="25" v-if="inputType=='text'"></u-icon>
							<u-icon custom-prefix="custom-icon-keyboard custom-icon" size="25" color="#888"
								v-if="inputType=='voice'"></u-icon>
						</view>
						<view
							style="flex: 1; height:65rpx;line-height: 65rpx; padding-top:0rpx;text-align: center; border-radius: 10px;"
							@touchstart="startRecording" @touchend="stopRecording" @touchmove="recordingMove">
							{{recordingTip}}
						</view>
						<view style="display: flex;" v-if="!isRecording">
							<view style="padding: 5px 10px;" @click="handleSend">
								<u-icon custom-prefix="custom-icon-send custom-icon"
									:color="sendable()? '#333':'#d0d0d0'" size="25"></u-icon>
							</view>
						</view>
					</view>
					<!--文字聊天-->
					<u-input border="none" v-if="inputType=='text'" v-model="chatMsg" maxlength="300"
						confirm-type="send" @confirm="handleSend" placeholder="有什么问题可以随时问我哦!" :show-confirm-bar="false"
						:adjust-position="false" @linechange="sendHeight" @focus="focus" @blur="blur" auto-height
						:focus="inputFocus">
						<template slot="prefix">
							<view style="padding: 5px 10px;" @click="handleSwitchInputType">
								<u-icon name="mic" size="25" v-if="inputType=='text'"></u-icon>
								<u-icon custom-prefix="custom-icon-keyboard custom-icon" size="20" color="#888"
									v-if="inputType=='voice'"></u-icon>
							</view>
						</template>
						<template slot="suffix">
							<view style="display: flex;">
								<view style="padding: 5px 5px; ">
									<u-icon name="plus-circle" size="25"></u-icon>
								</view>
								<view style="padding: 5px 10px;" @click="handleSend">
									<u-icon custom-prefix="custom-icon-send custom-icon"
										:color="sendable()? '#333':'#d0d0d0'" size="25"></u-icon>
								</view>
							</view>
						</template>
					</u-input>
					<u-toast ref="uToast"></u-toast>
				</view>
			</view>
		</view>

	</view>
</template>
<script>
	export default {
		data() {
			return {
				touchY: 0,
				chatid: -1,
				isCancel: false,
				isRecording: false,
				recordingTip: '按住 说话',
				inputFocus: false,
				historyVisible: false,
				typeContent: '',
				typeResText: '',
				inputType: 'text',
				date: '',
				weekday: '',
				//键盘高度
				keyboardHeight: 0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 0,
				userId: '',
				//发送的消息
				chatMsg: "",
				history: [],
				msgList: [],
				articles: []
			}
		},
		updated() {
			//页面更新时调用聊天消息定位到最底部
			this.scrollToBottom();
		},
		computed: {
			windowHeight() {
				return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight() {
				return this.bottomHeight + this.keyboardHeight;
				//return this.keyboardHeight
			},

		},

		onLoad(option) {
			this.loadArticles();
			uni.onKeyboardHeightChange(res => {
				//这里正常来讲代码直接写
				//this.keyboardHeight=this.rpxTopx(res.height)就行了
				//但是之前界面ui设计聊天框的高度有点高,为了不让键盘和聊天输入框之间距离差太大所以我改动了一下。
				this.keyboardHeight = this.rpxTopx(res.height)
				if (this.keyboardHeight < 0) this.keyboardHeight = 0;

			})
			this.scrollToBottom();
		},
		onShareAppMessage() {
			return {
				title: "耒耜AI大模型",
				path: '/pages/index/index',
			};
		},
		methods: {
			sendable() {
				return this.chatMsg == "" ? false : true;
			},
			loadArticles() {
				var params = {
					count: 4
				};
				this.api.get_article_list(params).then(lres => {
					if (lres.code == 1) {
						this.date = lres.date;
						this.weekday = lres.weekday;
						this.articles = lres.list;
					} else {
						uni.clearStorage();
						uni.reLaunch({
							url: "/pages/auth/login_wxcode"
						})
					}
				})
			},
			recordingMove(event) {
				var diffY = event.touches[0].clientY - this.touchY;
				if (diffY < -40) {
					this.recordingTip = "松手 取消";
					if (this.isCanel != true) {
						this.isCancel = true;
					}
				} else {
					this.recordingTip = "按住 说话";
					if (this.isCanel != false) {
						this.isCancel = false;
					}

				}
			},
			startRecording(event) {
				this.isRecording = true;
				console.log("开始录音");
				uni.vibrateShort();
				this.touchY = event.touches[0].clientY;

			},
			stopRecording() {
				this.isRecording = false;
				if (this.isCancel) {
					console.log("取消录音");
				} else {
					console.log("结束录音");
					this.isCancel = false;
				}
				uni.vibrateShort();
				this.recordingTip = "按住 说话";


			},
			createChat() {
				uni.reLaunch({
					url: "/pages/chat/index?type=new&q="
				})
			},
			handleViewHistory(item) {
				uni.navigateTo({
					url: "/pages/chat/index?type=history&chatid=" + item.chatid
				})
				this.historyVisible = false;
			},
			loadChatHistory(chatid) {
				this.api.get_history_detail({
					chatid: chatid
				}).then(res => {
					if (res.code == 1) {
						this.msgList = res.list;
					}
				})
			},

			openHistory() {
				this.api.get_history_list({}).then(res => {
					this.history = res.data;
				})
				this.historyVisible = true;
			},
			closeHistory() {
				this.historyVisible = false;
			},
			//复制
			copyContent(msg) {
				uni.setClipboardData({
					data: msg
				});
			},
			handleSwitchInputType() {
				this.inputType = this.inputType == 'text' ? 'voice' : 'text';
				if (this.inputType == 'text') {
					this.inputFocus = true;
				} else {
					this.inputFocus = false;
				}
			},
			focus() {
				this.scrollToBottom()
			},
			blur() {
				this.scrollToBottom()
			},
			// px转换成rpx
			rpxTopx(px) {
				let deviceWidth = uni.getSystemInfoSync().windowWidth
				let rpx = (750 / deviceWidth) * Number(px)
				return Math.floor(rpx)
			},
			// 监视聊天发送栏高度
			sendHeight() {
				setTimeout(() => {
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res => {
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				}, 100)
			},
			// 滚动至聊天底部
			scrollToBottom(e) {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) => {
						if (res[1].height > res[0].height) {
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				}, 100)
			},
			// 发送消息
			handleSend() {

				if (this.chatMsg == '') {
					return;
				}
				var msg = this.chatMsg;
				this.chatMsg = "";
				if (msg == "") {
					uni.showToast("内容为空");
				}
				uni.navigateTo({
					url: "/pages/chat/index?type=new&q=" + msg
				})


			},
			startTyping(text) {

				let currentIndex = 0;
				const typingSpeed = 10; // 打字速度，单位：毫秒
				var typedText = "";
				const timer = setInterval(() => {
					typedText += text[currentIndex];
					currentIndex++;
					this.msgList[this.msgList.length - 1].content = typedText;
					if (currentIndex >= text.length) {
						this.msgList[this.msgList.length - 1].actionVisible = true;
						clearInterval(timer);
						this.scrollToBottom()
					}
				}, typingSpeed);
			},
			waitingForResponse(msg) {
				// 创建新会话
				this.msgList.push({
					sender: 'ai',
					waiting: 1,
					actionVisible: false,
					content: ''
				});
				this.scrollToBottom();
				this.isWaiting = true;
				this.api.chat({
					newchat: false,
					chatid: this.chatid,
					content: msg,
				}).then(lres => {
					if (lres.code == 1) {
						this.isWaiting = false;
						this.msgList[this.msgList.length - 1].waiting = 0;
						this.chatid = lres.chatid;
						this.startTyping(lres.response);
						this.scrollToBottom();
					}
				});
			}
		}
	}
</script>
<style lang="scss" scoped>
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;

	view,
	button,
	text,
	input,
	textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	.logo {
		height: 200upx;
		width: 200upx;
		margin-top: 50upx;
		margin-left: auto;
		margin-right: auto;
	}

	.news-item {
		width: 100%;
		height: 35px;
		line-height: 35px;
		overflow: hidden;
		padding-left: 5px;
		text-overflow: ellipsis;
		white-space: nowrap;
		border-bottom: 1px solid #e7e7e7;
	}

	.logo-title {
		text-align: center;
		font-size: 18px;
		font-weight: bold;
	}

	/* 聊天消息 */
	.chat {
		.scroll-view {
			::-webkit-scrollbar {
				display: none;
				width: 0 !important;
				height: 0 !important;
				-webkit-appearance: none;
				background: transparent;
				color: transparent;
			}

			// background-color: orange;
			background-color: #ffffff;

			.chat-body {
				display: flex;
				flex-direction: column;
				align-content: center;
				padding-top: 23rpx;
				// background-color:skyblue;

				.self {
					justify-content: flex-end;
				}

				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;

					.right {
						background-color: $chatContentbgc;
					}

					.left {
						background-color: #FFFFFF;
					}

					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}

				}
			}
		}

		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 240rpx;
			background: #ffffff;
			transition: all 0.5s ease;

			.send-msg {
				display: flex;
				align-items: flex-end;
				padding: 16rpx 10rpx;
				width: 100%;
				min-height: 70rpx;
				position: fixed;
				bottom: 0;
				background: #ffffff;
				transition: all 0.1s ease;
			}

			.uni-textarea {
				width: 100%;
				padding-top: 5rpx;
				padding-bottom: 8rpx;
				border-radius: 12px;

				input {
					width: 100%;
					min-height: 60rpx;
					max-height: 500rpx;
					border-radius: 40rpx;
					font-size: 32rpx;
					color: #333333;
					line-height: 60rpx;
					padding: 5rpx 8rpx;
				}
			}
		}
	}

	/*历史会话相关样式*/
	.history-wraper {
		background-color: #fafafa;
		overflow-y: auto;
		height: 100vh;
		padding-bottom: 50px;
	}

	.history_section {
		line-height: 30px;
		height: 30px;
		padding-left: 5px;
		font-weight: bold;
	}
</style>